<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\facade\App;
use think\facade\Env;

class QiwechatMsg extends Command
{
    protected function configure() {
        $this->setName('QiwechatMsg')->setDescription("企微客服");
    }

    protected function execute(Input $input, Output $output) {
        ini_set('max_execution_time', 0);
        set_time_limit(0);
        
        // 获取access_token
        require(Env::get('think_path').'/../vendor/weworkapi/api/src/CorpAPI.class.php');
        $api = new \CorpAPI('ww488de754dc555ef3','_vIUjayI_IR24b2dTz_EJlj0OOGwvcI_MjVis994jV8');

        $chat_token = Db::name('config')->where([
            ['key','=','qi_weichat_chat_token'],
            // ['utime','>',date('Y-m-d H:i:s')]
        ])->value('value');
        // if (empty($chat_token)) {
        //     $api_param = [
        //         'api_key'=>'KIQRt82lSbkQ9Vjd',
        //         'ts'=>time()
        //     ];
        //     $api_param['sign'] = md5($api_param['api_key'].$api_param['ts'].'FH3jPmOln8vjm7uZ');
        //     $result = httpRequest('https://falv.biaocloud.cn/openapi/base/getToken',json_encode($api_param),'POST');
        //     $result = json_decode($result,true);
        //     if ($result['code'] == 2000) {
        //         $chat_token = $result['result']['data']['access_token'];
        //         Db::name('config')->where('key','qi_weichat_chat_token')->update([
        //             'value'=>$chat_token,
        //             'utime'=>$result['result']['data']['expiry_time']
        //         ]);
        //     }
        // }

        while(true){
            $starttime = time();
            try{
                $list = Db::name('qiwechat_msg')->where('status',0)->select();
                if (empty($list)) {
                    sleep(1);
                    continue;
                }
                foreach ($list as $k => $vo) {
                    $result = httpRequest('https://falv.biaocloud.cn/openapi/msg/chatapi?access_token='.$chat_token,json_encode([
                        'model'=>'ERNIE-4.0',
                        'message'=>$vo['message']
                    ]),'POST');
                    $result = json_decode($result,true);
                    if ($result['code'] == 2000) {
                        $reply = $result['result']['data']['reply'];
                      
                        $access_token = $api->GetAccessToken();
                        // 发送消息
                        $api_url = 'https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token='.$access_token;
                        $result = httpRequest($api_url,json_encode([
                            'touser'=>$vo['touser'],
                            'open_kfid'=>$vo['open_kfid'],
                            'msgid'=>uuidCreate(),
                            'msgtype'=>'text',
                            'text'=>['content'=>$reply]
                        ]),'POST',['Content-Type:application/json']);

                        Db::name('qiwechat_msg')->where('id',$vo['id'])->update(['status'=>1]);
                    }else{
                        Db::name('qiwechat_msg')->where('id',$vo['id'])->update(['status'=>-1]);
                    }
                }
            } catch (\Exception $e) {
                sleep(1);
                continue;
            }
            sleep(1);
        }
    }
}